package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    //依赖注入
    @Autowired
    private   CategoryMapper categoryMapper;

    //分类列表
    @Override
    @Cacheable(value = "category",key = "'findAll'")
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    //新增分类
    @Override
    @CacheEvict(value = "category",allEntries = true)
    public void save(Category category) {
        // 1. 补全信息
        // 1.1生成id
        long id = IdUtil.getSnowflake(1, 1).nextId();
        category.setId(id);
        // 1.2创建,更新时间
//        category.setCreateTime(new Date()); // todo 后期完善
//        category.setUpdateTime(new Date());
//        // 1.3 创建,更新人
//        category.setCreateUser(1L); // todo 后期完善
//        category.setUpdateUser(1L);

        // 2.调用mapper
        categoryMapper.save(category);
    }

    //修改分类
    @Override
    public void updateById(Category category) {
        // 1.补全信息
        // 1.1修改人修改时间
//        category.setUpdateUser(1L); // todo 后期完善
//        category.setUpdateTime(new Date());

        // 2.调用service
        categoryMapper.updateById(category);
    }

    //删除
    @Override
    @CacheEvict(value = "category",allEntries = true)
    public void deleteById(Long id) {
        // 1.根据分类id查询菜品数量,判断
        Long countDish = categoryMapper.countDishByCategoryId(id);
        if (countDish > 0) {
            throw new CustomException("该分类下有菜品不允许删除");
        }
        // 2.根据分类id查询套餐数量,判断
        Long countSetmeal = categoryMapper.countSetmealByCategoryId(id);
        if (countSetmeal > 0) {
            throw new CustomException("该分类下有套餐不允许删除");
        }
        //  3.根据id删除
        categoryMapper.deleteById(id);

    }

    //分类回显
    @Override
    public List<Category> findByType(Integer type) {
        // 构建条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        // 类型条件
        qw.eq(Category::getType,type);
        // 排序
        qw.orderByAsc(Category::getSort);
        // 返回结果
        return categoryMapper.selectList(qw);
    }
}
